package com.mkyong;

import java.io.File;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;

public class MailHandler {
	
	private JavaMailSender mailSender;
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void sendMail(String  from,String [] to,String [] cc,String subject,String content,String attachement) throws Exception{
		if(mailSender == null){
			throw new IllegalStateException("JavaMailSender not be initialized, please load bean JavaMailSenderImpl !");
		}
		if(StringUtils.isEmpty(from) || StringUtils.isEmpty(to)){
			   throw new IllegalStateException("Mail sender or receiver can not be empty.");
		   }
		   MimeMessage mimeMessge = mailSender.createMimeMessage();
		  
		   MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessge,true);
		   mimeMessageHelper.setFrom(from); 
		   mimeMessageHelper.setTo(to);
		   if(!StringUtils.isEmpty(cc)){
			   if(cc != null && cc.length > 0){
				   mimeMessageHelper.setCc(cc);
			   }
		   }
		   if(StringUtils.isEmpty(subject)){
			   mimeMessageHelper.setSubject("Subject:");
		   }else{
			   mimeMessageHelper.setSubject(subject);
		   }
		   if(StringUtils.isEmpty(content)){
			   mimeMessageHelper.setText("Dear all,<br/> This is a notice . See more details, check the attachment please ! </br> Best Regards.</br>",true);   
		   }else{
			   mimeMessageHelper.setText(content,true);   
		   }
		   File f = new File(attachement);
		   if(f.exists()){
			   FileSystemResource excelfile = new FileSystemResource(f);
			   mimeMessageHelper.addAttachment(MimeUtility.encodeWord(f.getName()),excelfile);  
		   }
		   mailSender.send(mimeMessge);
	}

}
